package base

import (
	"blog/types"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

// gorm.Model 的定义
type BaseModel struct {
	ID         int64        `gorm:"column:id;primaryKey" json:"id"`
	CreateTime types.MyTime `gorm:"column:create_time" json:"create_time"`
	CreateBy   int64        `gorm:"column:create_by" json:"create_by"`
	UpdateTime types.MyTime `gorm:"column:update_time" json:"update_time"`
	UpdateBy   int64        `gorm:"column:update_by" json:"update_by"`
}

func (u *BaseModel) BeforeCreate(tx *gorm.DB) (err error) {
	context := gin.Context{}
	userId, isExist := context.Get(types.StausConstant.UserId)
	if isExist == false {
		u.CreateBy = -1
	} else {
		u.CreateBy = cast.ToInt64(userId)
	}
	var time, _ = types.ParseNow()

	u.CreateTime = time

	return nil

}

func (u *BaseModel) BeforeSave(tx *gorm.DB) (err error) {

	context := gin.Context{}
	userId, isExist := context.Get(types.StausConstant.UserId)
	if isExist == false {

		tx.Statement.SetColumn("update_by", -1)

	} else {

		tx.Statement.SetColumn("update_by", cast.ToInt64(userId))

	}
	var time, _ = types.ParseNow()

	tx.Statement.SetColumn("update_time", time)

	return nil
}
